import java.util.ArrayList;
import java.util.Random;

public class Business extends Thread implements Runnable {
	private ArrayList<Worker> workers;
	private ColdStorage coldStorage;
	private Table table;
	private Stonepit stonepit;
	private VillageSquare villageSquare;
	private Random generator = new Random();
	private boolean interrupt = false;
	
	public Business(int jobs,int cap0, int cap1, int cap2) {
		Thread thread = new Thread(this);
		coldStorage = new ColdStorage(cap0);
		table = new Table(cap1);
		stonepit = new Stonepit(cap2);
		villageSquare = new VillageSquare();
		workers = new ArrayList<Worker>();
		for (int i = 2; i > 0; i--) {
			workers.add(BoarHunter.createBoarHunter(coldStorage, generator.nextInt(49)+1, jobs));
		}
		for (int i = 1; i > 0; i--) {
			workers.add(Cook.createCook(coldStorage, table, generator.nextInt(49)+1));
		}
		for (int i = 5; i > 0; i--) {
			workers.add(Lumberjack.createLumberjack(table, stonepit, generator.nextInt(49)+1));
		}
		for (int i = 2; i > 0; i--) {
			workers.add(Logistician.createLogistician(stonepit, villageSquare, generator.nextInt(49)+1));
		}
	}
	
	public void startBusiness() {
		for (Worker w : workers) {
			if (interrupt == false) {
				w.start();
			} else {
				break;
			}
		}
	}
	
	public void interruptBusiness() {
		for (Worker w : workers) {
			if (w != null) {
				w.interrupt();
			}
		}
		this.interrupt();
	}

	@Override
	public void run() {
		startBusiness();
		while(!villageSquare.checkPuttersDone()) {
			if (this.isInterrupted()) {
				break;
			}
			try {
				Thread.sleep(50);
			} catch (InterruptedException ex) {
				break;
			}
		}
		System.out.println(this);
	}

	@Override
	public String toString() {
		String out = "";
		for(Worker w:workers){
			out += w + System.getProperty("line.separator");
		}
		out += "Kühlkammer enthaelt " + coldStorage.count + "/" + coldStorage.limit + " Wildschwine" + System.getProperty("line.separator");
		out += "Tisch enthaelt "  + table.count + "/" + table.limit + " Wildschweinbraten" + System.getProperty("line.separator");
		out += "Steinbruch enthaelt "  + stonepit.count + "/" + stonepit.limit + " Christbaeume" + System.getProperty("line.separator");
		out += "Dorfplatz enthaelt "  + villageSquare.count + " Christbaeume" + System.getProperty("line.separator");
		return out;
	}
	
}